package org.nativejpa.query;

import org.nativejpa.support.sqlgen.SQLGenerator;

import javax.persistence.NamedNativeQuery;

/**
 * @author <a href="mailto:jfox.young@gmail.com">Young Yang</a>
 * @create 2009-9-14 17:58:03
 */
public class GeneratedNamedSQLTemplate extends NamedSQLTemplate {

    GeneratedNamedSQLTemplate(String name, String sqlTemplate, Class resultClass, String resultsetMapping, Class<?> defineClass) {
        super(name, sqlTemplate, resultClass, resultsetMapping, defineClass, DEFAULT_CACHE_NAME);
    }

    public static NamedSQLTemplate createInsertNamedSQLTemplate(Class<?> entityClass){
        String name = "_GENERATED_SQL_INSERT_" + entityClass.getName();
        if(!queryRepository.containsNamedSQLTemplate(name)) {
            // create NamedSQLTemplate as definedClass entityClass
            GeneratedNamedSQLTemplate sqlTemplate = new GeneratedNamedSQLTemplate(name, SQLGenerator.buildInsertSQL(entityClass), Integer.class, "", entityClass);
            queryRepository.registerNamedSQLTemplate(sqlTemplate);
        }
        return queryRepository.getNamedSQLTemplate(name);
    }

    public static NamedSQLTemplate createDeleteNamedSQLTemplate(Class<?> entityClass){
        String name = "_GENERATED_SQL_DELETE_" + entityClass.getName();
        if(!queryRepository.containsNamedSQLTemplate(name)) {
            GeneratedNamedSQLTemplate sqlTemplate = new GeneratedNamedSQLTemplate(name, SQLGenerator.buildDeleteByIdSQL(entityClass), Integer.class, "", entityClass);
            queryRepository.registerNamedSQLTemplate(sqlTemplate);
        }
        return queryRepository.getNamedSQLTemplate(name);
    }

    public static NamedSQLTemplate createUpdateNamedSQLTemplate(Class<?> entityClass){
        String name = "_GENERATED_SQL_UPDATE_" + entityClass.getName();
        if(!queryRepository.containsNamedSQLTemplate(name)) {
            GeneratedNamedSQLTemplate sqlTemplate = new GeneratedNamedSQLTemplate(name, SQLGenerator.buildUpdateSQL(entityClass), Integer.class, "", entityClass);
            queryRepository.registerNamedSQLTemplate(sqlTemplate);
        }
        return queryRepository.getNamedSQLTemplate(name);
    }

    public static NamedSQLTemplate createSelectNamedSQLTemplate(Class<?> entityClass){
        String name = "_GENERATED_SQL_SELECT_" + entityClass.getName();
        if(!queryRepository.containsNamedSQLTemplate(name)) {
            GeneratedNamedSQLTemplate sqlTemplate = new GeneratedNamedSQLTemplate(name, SQLGenerator.buildSelectByIdSQL(entityClass), entityClass, "", entityClass);
            queryRepository.registerNamedSQLTemplate(sqlTemplate);
        }
        return queryRepository.getNamedSQLTemplate(name);
    }

    public boolean isGenerated() {
        return false;
    }

}
